<template>
  <div
    class="topic-card"
    :class="{
      'topic-card--hot': isHot,
      'topic-card--large': size === 'large'
    }"
    @click="handleClick"
  >
    <!-- 封面图片 -->
    <div class="topic-cover">
      <img 
        :src="getMediaUrl(topic.coverImage) || getDefaultCover()" 
        :alt="topic.name"
        class="cover-image"
      >
      <!-- 圆形Logo覆盖在封面上 -->
      <div class="topic-logo">
        <img 
          :src="getMediaUrl(topic.avatar) || getDefaultAvatar()" 
          :alt="topic.name"
          class="avatar"
          :style="{ width: (size === 'large' ? 70 : 60) + 'px', height: (size === 'large' ? 70 : 60) + 'px' }"
        >
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="topic-content">
      <h3 class="topic-name">{{ topic.name }}</h3>
      <p class="topic-description" v-if="topic.description">
        {{ topic.description }}
      </p>
      
      <!-- 统计信息移到底部 -->
      <div class="topic-stats" v-if="showActions">
        <span class="stat-item">
          <el-icon><User /></el-icon>
          {{ formatCount(topic.followerCount || 0) }} followers
        </span>
      </div>

      <!-- 关注按钮 -->
      <div class="topic-actions" v-if="showActions" @click.stop>
        <el-button
          :type="topic.isFollowed ? '' : 'primary'"
          :loading="followLoading"
          size="small"
          class="follow-btn"
          @click="handleFollow"
        >
          {{ topic.isFollowed ? 'Following' : 'Follow' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {TrendCharts} from '@element-plus/icons-vue'
import {getMediaUrl} from '@/utils/media'
import {formatCount} from '@/utils/format'
import {toggleFollowTopic} from '@/api/topic'
import {useUserStore} from '@/stores/user'

const props = defineProps({
  topic: {
    type: Object,
    required: true
  },
  size: {
    type: String,
    default: 'default', // default, large
    validator: (value) => ['default', 'large'].includes(value)
  },
  showActions: {
    type: Boolean,
    default: true
  },
  clickable: {
    type: Boolean,
    default: true
  },
  isHot: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['click', 'follow-change'])

const userStore = useUserStore()
const followLoading = ref(false)

// 生成默认封面图片（渐变色）
const getDefaultCover = () => {
  const gradients = [
    '#667eea,#764ba2',
    '#f093fb,#f5576c',
    '#4facfe,#00f2fe',
    '#43e97b,#38f9d7',
    '#fa709a,#fee140',
    '#30cfd0,#330867',
    '#a8edea,#fed6e3',
    '#ff9a9e,#fecfef',
  ]
  const index = (props.topic.id || 0) % gradients.length
  const [color1, color2] = gradients[index].split(',')
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">
    <defs>
      <linearGradient id="g${index}" x1="0%" y1="0%" x2="100%" y2="100%">
        <stop offset="0%" style="stop-color:${color1};stop-opacity:1"/>
        <stop offset="100%" style="stop-color:${color2};stop-opacity:1"/>
      </linearGradient>
    </defs>
    <rect width="400" height="200" fill="url(#g${index})"/>
  </svg>`
  return `data:image/svg+xml,${encodeURIComponent(svg)}`
}

// 生成默认头像（纯色圆形）
const getDefaultAvatar = () => {
  const colors = ['#667eea', '#f093fb', '#4facfe', '#43e97b', '#fa709a', '#30cfd0', '#a8edea', '#ff9a9e']
  const index = (props.topic.id || 0) % colors.length
  const color = colors[index]
  const initial = props.topic.name?.charAt(0).toUpperCase() || '?'
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
    <circle cx="100" cy="100" r="100" fill="${color}"/>
    <text x="100" y="100" text-anchor="middle" dominant-baseline="central" font-size="80" fill="white" font-weight="600" font-family="Arial, sans-serif">${initial}</text>
  </svg>`
  return `data:image/svg+xml,${encodeURIComponent(svg)}`
}

const handleClick = () => {
  if (props.clickable) {
    emit('click', props.topic)
  }
}

const handleFollow = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  followLoading.value = true
  try {
    const response = await toggleFollowTopic(props.topic.id)
    if (response.code === 200) {
      // 更新关注状态
      props.topic.isFollowed = !props.topic.isFollowed
      
      // 更新关注数
      if (props.topic.isFollowed) {
        props.topic.followerCount = (props.topic.followerCount || 0) + 1
        ElMessage.success('Followed successfully')
      } else {
        props.topic.followerCount = Math.max(0, (props.topic.followerCount || 0) - 1)
        ElMessage.success('Unfollowed')
      }
      
      emit('follow-change', {
        topicId: props.topic.id,
        isFollowed: props.topic.isFollowed
      })
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('关注话题失败:', error)
    ElMessage.error('操作失败')
  } finally {
    followLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.topic-card {
  background: white;
  border-radius: 8px;
  border: 1px solid #dee0e1;
  transition: all 0.2s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 280px;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  // 封面图片区域
  .topic-cover {
    position: relative;
    width: 100%;
    height: 140px;
    overflow: hidden;
    background: #f5f5f5;

    .cover-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }

    // Logo圆形覆盖（居中）
    .topic-logo {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 1000;

      .avatar {
        display: block;
        border-radius: 10px;
        object-fit: cover;
        // background: #ffffff;
        // border: 3px solid #ffffff;
        // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }
    }
  }

  // 内容区域
  .topic-content {
    padding: 16px;
    display: flex;
    flex-direction: column;
    flex: 1;

    .topic-name {
      font-size: 16px;
      font-weight: 600;
      color: #1a1a1a;
      margin: 0 0 8px 0;
      line-height: 1.3;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .topic-description {
      font-size: 13px;
      color: #636466;
      margin: 0 0 12px 0;
      line-height: 1.5;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
      min-height: 40px;
    }

    .topic-stats {
      display: flex;
      justify-content: center;
      margin-top: auto;
      padding-top: 8px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 13px;
        color: #939598;

        .el-icon {
          font-size: 14px;
        }
      }
    }

    .topic-actions {
      display: flex;
      justify-content: center;
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #e4e6e8;

      .follow-btn {
        min-width: 80px;
        border-radius: 16px;
        font-size: 13px;
        font-weight: 500;
        
        &.el-button--primary {
          background: #2e69ff;
          border-color: #2e69ff;
          
          &:hover {
            background: #1557ff;
            border-color: #1557ff;
          }
        }
        
        &.el-button--default {
          color: #636466;
          border-color: #dee0e1;
          
          &:hover {
            background: #f7f7f8;
          }
        }
      }
    }
  }

  // 大尺寸样式
  &--large {
    height: 280px;
    
    .topic-cover {
      height: 180px;
    }

    .topic-content {
      padding: 20px;

      .topic-name {
        font-size: 18px;
        margin-bottom: 10px;
      }

      .topic-description {
        font-size: 14px;
        margin-bottom: 16px;
        min-height: 42px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .topic-card {
    .topic-cover {
      height: 120px;
    }

    .topic-content {
      padding: 12px;

      .topic-name {
        font-size: 15px;
      }

      .topic-description {
        font-size: 12px;
        min-height: 36px;
      }

      .topic-stats .stat-item {
        font-size: 12px;
      }
    }

    &--large {
      .topic-cover {
        height: 140px;
      }
    }
  }
}
</style>
